<template>
  <div class="timer-panel">
    <div class="panel-header">
      <h3>⏱️ 计时器</h3>
    </div>

    <!-- 无计时器状态 -->
    <div v-if="!timerState.recordId" class="empty-state">
      <el-empty description="选择任务开始计时">
        <template #image>
          <div class="empty-icon">⏰</div>
        </template>
      </el-empty>
    </div>

    <!-- 有计时器状态 -->
    <div v-else class="timer-content">
      <!-- 任务信息 -->
      <div class="task-info">
        <div class="task-title">{{ timerState.taskTitle }}</div>
        <el-tag v-if="timerState.categoryName" size="small" :color="timerState.categoryColor">
          {{ timerState.categoryName }}
        </el-tag>
      </div>

      <!-- 计时显示 -->
      <div class="timer-display">
        {{ formattedTime }}
      </div>

      <!-- 状态指示 -->
      <div class="timer-status">
        <el-tag :type="statusType" size="large">
          {{ statusText }}
        </el-tag>
      </div>

      <!-- 控制按钮 -->
      <div class="timer-controls">
        <el-button
          v-if="timerState.isRunning"
          type="warning"
          size="large"
          @click="handlePause"
          :loading="loading"
        >
          <el-icon><VideoPause /></el-icon>
          暂停
        </el-button>

        <el-button
          v-if="timerState.isPaused"
          type="primary"
          size="large"
          @click="handleResume"
          :loading="loading"
        >
          <el-icon><VideoPlay /></el-icon>
          继续
        </el-button>

        <el-button
          type="danger"
          size="large"
          @click="handleStop"
          :loading="loading"
        >
          <el-icon><CircleClose /></el-icon>
          停止
        </el-button>
      </div>

      <!-- 今日统计 -->
      <div class="today-stats">
        <div class="stat-item">
          <span class="stat-label">今日累计</span>
          <span class="stat-value">{{ formatDuration(todayTotal) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getCurrentTimer,
  pauseTimer,
  resumeTimer,
  stopTimer,
  getTimerStatistics
} from '../api/timer'

const loading = ref(false)
const todayTotal = ref(0)
let timerInterval = null

// 计时器状态
const timerState = ref({
  recordId: null,
  taskId: null,
  taskTitle: '',
  categoryName: '',
  categoryColor: '',
  startTime: null,
  currentDuration: 0,
  isRunning: false,
  isPaused: false
})

// 格式化时间显示（HH:MM:SS）
const formattedTime = computed(() => {
  const seconds = timerState.value.currentDuration
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
})

// 状态文本
const statusText = computed(() => {
  if (timerState.value.isRunning) return '运行中'
  if (timerState.value.isPaused) return '已暂停'
  return ''
})

// 状态类型
const statusType = computed(() => {
  if (timerState.value.isRunning) return 'success'
  if (timerState.value.isPaused) return 'warning'
  return 'info'
})

// 格式化持续时长
const formatDuration = (seconds) => {
  if (!seconds) return '0分钟'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟`
  } else {
    return `${seconds}秒`
  }
}

// 加载当前计时器
const loadCurrentTimer = async () => {
  try {
    const response = await getCurrentTimer()
    const timer = response.data
    
    if (timer) {
      timerState.value = {
        recordId: timer.recordId,
        taskId: timer.taskId,
        taskTitle: timer.taskTitle,
        categoryName: timer.categoryName,
        categoryColor: timer.categoryColor,
        startTime: timer.startTime,
        currentDuration: timer.duration || 0,
        isRunning: timer.status === 'RUNNING',
        isPaused: timer.status === 'PAUSED'
      }
      
      // 保存到localStorage
      saveTimerState()
      
      // 如果是运行中，启动前端计时器
      if (timerState.value.isRunning) {
        startFrontendTimer()
      }
    }
  } catch (error) {
    console.error('加载当前计时器失败:', error)
  }
}

// 加载今日统计
const loadTodayStats = async () => {
  try {
    const response = await getTimerStatistics('today')
    todayTotal.value = response.data.todayTotal || 0
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 暂停计时
const handlePause = async () => {
  loading.value = true
  try {
    await pauseTimer(timerState.value.recordId)
    timerState.value.isRunning = false
    timerState.value.isPaused = true
    stopFrontendTimer()
    saveTimerState()
    ElMessage.success('计时已暂停')
  } catch (error) {
    console.error('暂停计时失败:', error)
    ElMessage.error('暂停计时失败')
  } finally {
    loading.value = false
  }
}

// 继续计时
const handleResume = async () => {
  loading.value = true
  try {
    await resumeTimer(timerState.value.recordId)
    timerState.value.isRunning = true
    timerState.value.isPaused = false
    startFrontendTimer()
    saveTimerState()
    ElMessage.success('计时已继续')
  } catch (error) {
    console.error('继续计时失败:', error)
    ElMessage.error('继续计时失败')
  } finally {
    loading.value = false
  }
}

// 停止计时
const handleStop = async () => {
  loading.value = true
  try {
    await stopTimer(timerState.value.recordId)
    stopFrontendTimer()
    clearTimerState()
    await loadTodayStats()
    ElMessage.success('计时已停止')
  } catch (error) {
    console.error('停止计时失败:', error)
    ElMessage.error('停止计时失败')
  } finally {
    loading.value = false
  }
}

// 启动前端计时器
const startFrontendTimer = () => {
  stopFrontendTimer() // 先停止已有的
  
  timerInterval = setInterval(() => {
    timerState.value.currentDuration++
    
    // 每30秒保存一次状态
    if (timerState.value.currentDuration % 30 === 0) {
      saveTimerState()
    }
  }, 1000)
}

// 停止前端计时器
const stopFrontendTimer = () => {
  if (timerInterval) {
    clearInterval(timerInterval)
    timerInterval = null
  }
}

// 保存计时器状态到localStorage
const saveTimerState = () => {
  localStorage.setItem('timerState', JSON.stringify(timerState.value))
}

// 从localStorage恢复计时器状态
const restoreTimerState = () => {
  const saved = localStorage.getItem('timerState')
  if (saved) {
    try {
      const state = JSON.parse(saved)
      if (state.recordId) {
        timerState.value = state
        
        // 如果是运行中，启动前端计时器
        if (state.isRunning) {
          startFrontendTimer()
        }
      }
    } catch (error) {
      console.error('恢复计时器状态失败:', error)
    }
  }
}

// 清除计时器状态
const clearTimerState = () => {
  timerState.value = {
    recordId: null,
    taskId: null,
    taskTitle: '',
    categoryName: '',
    categoryColor: '',
    startTime: null,
    currentDuration: 0,
    isRunning: false,
    isPaused: false
  }
  localStorage.removeItem('timerState')
}

// 暴露方法给父组件
defineExpose({
  loadCurrentTimer,
  timerState
})

onMounted(() => {
  // 先尝试从localStorage恢复
  restoreTimerState()
  
  // 然后从服务器加载最新状态
  loadCurrentTimer()
  loadTodayStats()
})

onUnmounted(() => {
  stopFrontendTimer()
})
</script>

<style scoped>
.timer-panel {
  background: white;
  border-radius: 8px;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  margin-bottom: 20px;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 80px;
  opacity: 0.3;
}

.timer-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.task-info {
  text-align: center;
  margin-bottom: 30px;
}

.task-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.timer-display {
  font-size: 64px;
  font-weight: bold;
  color: #409eff;
  font-family: 'Courier New', monospace;
  margin: 40px 0;
  text-align: center;
}

.timer-status {
  margin-bottom: 30px;
}

.timer-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 40px;
}

.today-stats {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  width: 100%;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}
</style>
